﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using cs499.Database;

namespace cs499.Locations
{
    public partial class ImportBuilding : System.Web.UI.Page
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session["ImportBuildingLabelText"] != null && IsPostBack)
            {
                ImportBuildingLabel.Text = (string)HttpContext.Current.Session["ImportBuildingLabelText"];
                //OKButton.Enabled = false;
            }
            else if (IsPostBack)
            {
                ImportBuildingLabel.Text = "";
            }
            else
            {
                ImportBuildingLabel.Text = "";
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            LinkButton locationsMenuButton = (LinkButton)Master.FindControl("LoginView").FindControl("LocationsMenuButton");
            locationsMenuButton.CssClass = "selected";

            if (ImportBuildingLabel.Text != "") return;
            if (HttpContext.Current.Session["CurrentDepartmentId"] != null)
            {
                int CurrentDepartmentId = (int)HttpContext.Current.Session["CurrentDepartmentId"];
                cs499.Database.Department CurrentDepartment = Database.ListOfDepartment.GetDepartment(ID: CurrentDepartmentId);
                ImportBuildingLabel.Text = "Input file containing information for new Buildings";
            }
            else
            {
                Response.Redirect("~/Locations/ListLocations.aspx");
            }
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Locations/ListLocations.aspx");
        }

        protected void ImportBuildingFileUpload_DataBinding(object sender, EventArgs e)
        {
            HttpContext.Current.Session["ImportBuildingLabelText"] = "Bad parse";
            Server.Transfer("~/Locations/ImportBuilding.aspx", true);
        }

        protected void OKButton_Click(object sender, EventArgs e)
        {
            if (!ImportBuildingFileUpload.HasFile)
            {
                String errmsg = "User must Specify File";
                if (ImportBuildingLabel.Text != errmsg)
                {
                    HttpContext.Current.Session["ImportBuildingLabelText"] = errmsg;
                    Server.Transfer("~/Locations/ImportBuilding.aspx", true);
                }
                return;
            }

            System.IO.StreamReader streamReader = new System.IO.StreamReader(ImportBuildingFileUpload.FileContent); 
            Model1Container db = new Model1Container();

            string line = null;
            int lineNumber = 0;
            List<string> buildingsThatAlreadyExist = new List<string>();
            List<string> buildingsAdded = new List<string>();
            System.Text.StringBuilder importStatus = new System.Text.StringBuilder();

            while ((line = streamReader.ReadLine()) != null)
            {
                lineNumber++;

                //only parse non-comment lines
                if (!line.StartsWith("#") && line != "" && line.Replace(",", "") != "")
                {
                    string[] fields = line.Split(',');
                    Building building = new Building();
                    try
                    {
                        //first bust out all of the field values, and assign what's easy
                        building.Code = fields[0];
                        building.Name = fields[1];

                        int currentDepartmentId = (int)HttpContext.Current.Session["CurrentDepartmentId"];
                        Department department = db.Set<Department>().FirstOrDefault(dep => (dep.Id == currentDepartmentId));

                        Building queriedBuilding = department.GetBuilding(buildingcode: building.Code);
                        if (queriedBuilding == null)
                        {
                            //set the fields to create the Place roll-up record as well
                            building.DepartmentId = department.Id;
                            building.PlaceName = building.Code;

                            //add new course to set that will go to database
                            db.Set<Building>().Add(building);

                            buildingsAdded.Add(building.Name + " (" + building.Code + ")");
                        }
                        else
                        {
                            //keep track of what we're not adding
                            buildingsThatAlreadyExist.Add(building.Name + " (" + building.Code + ")");
                        }
                    }
                    catch (Exception /*ex*/)
                    {
                        importStatus.Append("Line #" + lineNumber + ": " + line + "<br />");
                    }
                }
            }

            if (importStatus.Length != 0) //means we have reported errors
            {
                //insert the explanatory message before the errors
                importStatus.Insert(0, "There was an error processing the following line(s) in " + ImportBuildingFileUpload.FileName + "<br />");
                //add an extra space after the errors
                importStatus.Append("<br />");
                //tell the user what to do
                importStatus.Append("Please investigate and retry the import. No records were committed to the application.");

                ImportBuildingLabel.Text = importStatus.ToString();
                return;
            }
            else
            {
                //after all lines are successfully processed, then commit the changes to the database
                db.SaveChanges();

                //tell the user how many objects we imported
                importStatus.Append("Number of buildings imported: " + buildingsAdded.Count + "<br />");

                if (buildingsAdded.Count > 0)
                {
                    //tell the user which objects were imported
                    importStatus.Append("Buildings added: <ul>");
                    foreach (string slot in buildingsAdded)
                        importStatus.Append("<li>" + slot + "</li>");
                    importStatus.Append("</ul>");
                }
                
                //if we didn't import anything, tell the user
                if (buildingsThatAlreadyExist.Count > 0)
                {
                    importStatus.Append("<br />There were items that were not imported because they already existed in the application.<br />");
                    importStatus.Append("Number of buildings skipped: " + buildingsThatAlreadyExist.Count + "<br />");
                    //importStatus.Append("Time slots skipped: " + string.Join(", ", buildingsThatAlreadyExist.ToArray()));

                    importStatus.Append("Buildings skipped: <ul>");
                    foreach (string slot in buildingsThatAlreadyExist)
                        importStatus.Append("<li>" + slot + "</li>");
                    importStatus.Append("</ul>");
                }

                ImportBuildingLabel.Text = importStatus.ToString();
            }
        }
    }
}